﻿using CqCore.Logging;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using System.Threading.Tasks;

namespace CqBuiltinService.Requests
{
    public class RequestingTrackFilter : IAsyncActionFilter
    {
        readonly ILogRecorder logger;

        public RequestingTrackFilter(ILogRecorder<RequestingTrackFilter> logger)
        {
            this.logger = logger;
        }

        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            logger.Info(new EventData
            {
                Type = $"{context.ActionDescriptor.DisplayName}",
                Message = "Requesting",
                Labels = {
                    ["TraceId"] = context.HttpContext.TraceIdentifier,
                    ["Method"] = context.HttpContext.Request.Method,
                    ["Path"] = context.HttpContext.Request.Path.Value,
                    ["Query"] = context.HttpContext.Request.QueryString.Value,
                    ["Arguments"] = JsonConvert.SerializeObject(context.ActionArguments)
                }
            });

            await next();
        }
    }
}
